#include"List.h"

ListNode* BuyListNode( LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;

}
//不用传参  将返回值返回给结构体指针
ListNode* ListNodeInit()
{
	ListNode* phead = BuyListNode(0);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void ListNodePintf(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	printf("NULL<=>");
	while (cur != phead)
	{
		printf("%d<=>", cur->data);
		cur = cur->next;
	}
	printf("\n");
}


void ListNodePushBack(ListNode* phead, LTDataType x)
{
	assert(phead);
	//新结点
	ListNode* newnode = BuyListNode(x);
	//找尾
	ListNode* tail = phead->prev;
	//连接
	newnode->prev = tail;
	tail->next = newnode;
	newnode->next = phead;
	phead->prev = newnode;
}

void ListNodePopBack(ListNode* phead)
{
	assert(phead);
	//检查空链表 phead->next == phead 就是空链表
	assert(phead->next != phead);
	//找尾
	ListNode* tail = phead->prev;
	//尾的前一个
	ListNode* tailprev = tail->prev;
	//连接
	tailprev->next = phead;
	phead->prev = tailprev;
	//删除
	free(tail);

}

void ListNodePushFront(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = BuyListNode(x);
	//找之前的头结点
	ListNode* pheadnext = phead->next;

	//连接新结点
	phead->next = newnode;
	newnode->prev = phead;

	newnode->next = pheadnext;
	pheadnext->prev = newnode;

}


void ListNodePophFront(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	ListNode* first = phead->next;
	ListNode* second = phead->next->next;
	free(first);
	phead->next = second;
	second->prev = phead;
}

ListNode* FindPos(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur!=phead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void ListNodeInsert(ListNode* pos, LTDataType x)
{
	assert(pos);

	ListNode* posprev = pos->prev;
	ListNode* newnode = BuyListNode(x);
	posprev->next = newnode;
	newnode->prev = posprev;

	newnode->next = pos;
	pos->prev = newnode;

}

void ListNodePosErase(ListNode* pos)
{
	assert(pos);
	//保存pos前一个
	ListNode* posprev = pos->prev;
	//保存pos后一个
	ListNode* posnext = pos->next;

	free(pos);
	posprev->next = posnext;
	posnext->prev = posprev;

}





void ListNodeDestroyed(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	ListNode* curnext = NULL;
	while (cur != phead)
	{
		curnext = cur->next;
		free(cur);
		cur = curnext;
	}
}